import TIM from 'tim-js-sdk'
const logkey = 'xone-tim'

// https://cloud.tencent.com/document/product/269/37411

export let tim = {
  init() {
    if(this.inited) return
    this.inited = true
    this.tim = TIM.create({
      SDKAppID: uni.$x.tcloud.sdkAppId
    })
    this.ready = false
    this.netState = ''
    this.repeatIds = []

    // tim.setLogLevel(0)
    this.tim.setLogLevel(1)

    this.tim.on(TIM.EVENT.SDK_READY, this._onReady=event=>this.onReady(event))
    this. tim.on(TIM.EVENT.SDK_NOT_READY, this._onNotReady=event=>this.onNotReady(event))
    this.tim.on(TIM.EVENT.KICKED_OUT, this._onKickedOut=event=>this.onKickedOut(event))
    this.tim.on(TIM.EVENT.NET_STATE_CHANGE, this._onNetStatusChange=event=>this.onNetStatusChange(event))
    this.tim.on(TIM.EVENT.PROFILE_UPDATED, this._onProFileUpdated=event=>this.onProFileUpdated(event))

    this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this._onMessagesReceived=event=>this.onMessagesReceived(event))
    this.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this._onConversationListUpdated=event=>this.onConversationListUpdated(event))

    this.tim.on(TIM.EVENT.ERROR, this._onError=event=>this.onError(event))
  },
  destory() {
    this.tim.off(TIM.EVENT.SDK_READY, this._onReady)
    this. tim.off(TIM.EVENT.SDK_NOT_READY, this._onNotReady)
    this.tim.off(TIM.EVENT.KICKED_OUT, this._onKickedOut)
    this.tim.off(TIM.EVENT.NET_STATE_CHANGE, this._onNetStatusChange)
    this.tim.off(TIM.EVENT.PROFILE_UPDATED, this._onProFileUpdated)

    this.tim.off(TIM.EVENT.MESSAGE_RECEIVED, this._onMessagesReceived)
    this.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, this._onConversationListUpdated)

    this.tim.off(TIM.EVENT.ERROR, this._onError)
    this.inited = false
  },
  login() {
    this.logining = true
    return this.tim.login({
      userID: uni.$x.tcloud.userId,
      userSig: uni.$x.tcloud.userSig
    })
  },
  logout() {
    this.logining = false
    return this.tim.logout()
  },
  updateProfile(info) {
    // {nick, avatar, gender, birthday}={}
    return this.tim.updateMyProfile(info)
  },
  getMyProfile() {
    return this.tim.getMyProfile().then(res=>{
      return  res.data
    })
  },


  
  getConversationList(options) {
    return this.tim.getConversationList(options)
  },
  /**
   * 
   * const messageList = imResponse.data.messageList; // 消息列表。
   * const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
   * const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。isCompleted 为 true 时，nextReqMessageID 为 ""。
   */
  getMessageList(conversationId,nextReqMessageId) {
    return this.tim.getMessageList({
      conversationID: conversationId, 
      nextReqMessageID: nextReqMessageId
    })
  },
  



  createGroup(name, groupId, {type, memberList, introduction, notification, avatar, groupCustomField}={}) {
    name = name||groupId||String(new Date().getTime())
    return this.tim.createGroup({
      name,
      groupID: groupId,
      type,
      introduction, notification, avatar,
      memberList,
      groupCustomField
    })
  },
  dismissGroup(groupId) {
    return this.tim.dismissGroup(groupId)
  },
  joinGroup(groupID, applyMessage) {
    return this.tim.joinGroup({groupID,applyMessage})
  },
  quitGroup(groupId) {
    return this.tim.quitGroup(groupId)
  },
  updateGroupProfile(groupId, {name, type, memberList, introduction, notification, avatar, groupCustomField}={}) {
    console.log('updateGroupProfile', groupId, introduction, notification)
    return this.tim.updateGroupProfile({
      groupID: groupId,
      name,
      type,
      introduction, notification, avatar,
      memberList,
      groupCustomField
    })
  },
  setGroupMemberNameCard(groupId, userId, nameCard) {
    return this.tim.setGroupMemberNameCard({
      groupID: groupId,
      userID: userId, 
      nameCard 
    })
  },
  getGroupProfile(groupId) {
    return this.tim.getGroupProfile({groupID: groupId})
  },




  sendTextMessage(to, text, {isGroup}={}) {
    let messageInstance = this.tim.createTextMessage({
      to, 
      conversationType: isGroup?this.TIM.TYPES.CONV_GROUP:this.TIM.TYPES.CONV_C2C,
      payload: {
        text
      }
    })
    return this.tim.sendMessage(messageInstance)
  },
  sendCustomMessage(to, data='', description='', extension='', {isGroup}={}) {
    let message = this.tim.createCustomMessage({
      to,
      conversationType: isGroup?this.TIM.TYPES.CONV_GROUP:this.TIM.TYPES.CONV_C2C,
      payload: {
        data,
        description,
        extension,
      }
    })

    return this.tim.sendMessage(message, {
      // onlineUserOnly: true
    });
  },
  sendImgMessage(to, imgPath, {isGroup}={}) {
    let messageInstance = this.tim.createTextMessage({
      to, 
      conversationType: isGroup?this.TIM.TYPES.CONV_GROUP:this.TIM.TYPES.CONV_C2C,
      payload: {
        text:'#&sendImg:&'+imgPath
      }
    })
    return this.tim.sendMessage(messageInstance)
  },
  // sendImgMessage(to, file, {isGroup}={}) {
  //   let messageInstance = this.tim.createImageMessage({
  //     to, 
  //     conversationType: isGroup?this.TIM.TYPES.CONV_GROUP:this.TIM.TYPES.CONV_C2C,
  //     payload: {
  //       file: file
  //     },
  //     onProgress: (event)=>{ console.log('file uploading:', event) }
  //   })
  //   return this.tim.sendMessage(messageInstance)
  // },


  onReady(event){
    this.ready = true
    this.netState = 'connected'
    console.log(logkey, 'ready', this.ready, this.netState)
    uni.$emit(logkey+'-ready-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
    uni.$emit(logkey+'-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
  },
  onNotReady(event){
    this.ready = false
    console.log(logkey, 'ready', this.ready, this.netState)
    uni.$emit(logkey+'-ready-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
    uni.$emit(logkey+'-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
  },
  onKickedOut(event){
    this.ready = false
    console.log(logkey, 'kickedout', this.ready, this.netState)
    uni.$emit(logkey+'-kickedout', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
    uni.$emit(logkey+'-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
  },
  onNetStatusChange(event){
    this.netState = event.data.state
    console.log(logkey, 'net state', this.ready, this.netState)
    uni.$emit(logkey+'-net-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
    if(this.ready) {
      uni.$emit(logkey+'-status', this.logining&&this.ready&&this.netState==='connected', this.ready, this.netState==='connected', this.logining)
    }else{
      if(this.logining) this.login()
    }
  },
  onProFileUpdated(event){
    uni.$emit(logkey+'-profile-updated', event)
  },
  onMessagesReceived(event){
    event.data.forEach(v=>{
      // if(this.repeatIds.find(v.ID)) return
      // this.repeatIds.push(v.ID)
      // this.repeatIds.shift()
      this.onMessageReceived(v)
    })
  },
  onMessageReceived(event){
    uni.$emit(logkey+'-message', event)
  },
  onConversationListUpdated(event) {
    uni.$emit(logkey+'-conversation-list-updated', event)
  },
  onError(event){
    console.error(logkey, 'error', event.data)
  }
}

export default function($x, {
	timExtend
}={}, app) {
	Object.assign(tim, timExtend||{})
	$x.tim = tim
  $x.tim.TIM = TIM
}